import { defineStore } from 'pinia'
import { ref } from 'vue'
import { IMenu } from '@/api/menu/type';
import router from '@/router';

export const useTagsViewStore = defineStore('tagsView', () => {
  const menus = ref<IMenu[]>([]);
  const menu = ref<IMenu>();
  const handles = ref<((menu?: IMenu) => void)[]>([]);

  // 添加Tag
  const addTag = (m: IMenu, isClear: boolean = false) => {
    if (isClear) {
      menus.value = [];
    }

    menu.value = m;
    if (!menus.value.includes(m)) {
      menus.value.push(m)
    }

    toLink();
  }

  const deleteTag = (m: IMenu) => {
    if (menus.value.includes(m)) {
      menus.value.splice(menus.value.indexOf(m), 1);
    }

    if (menu.value == m) {
      menu.value = menus.value[menus.value.length - 1];
    }
    toLink();
  }

  const handleToLink = (callBack: (menu?: IMenu) => void) => {
    if (!handles.value.includes(callBack)) {
      handles.value.push(callBack);
    }
  }

  const toLink = () => {
    if (menu.value == undefined) {
      return;
    }

    if (menu.value.type == 3) {
      window.location.href = menu.value.path ?? "";
    }
    else {
      router.push({
        path: menu.value.redirect ?? ""
      })
    }

    handles.value.forEach(callBack => callBack(menu.value));
  }

  return { menu, menus, addTag, deleteTag, toLink, handleToLink }
});